﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Web.controls
{
    public partial class GroupTree : System.Web.UI.UserControl
    {
        public bool EnabledPhRight { get; set; }

        public GroupTreeType GroupTreeType { get; set; }

        public DataSet pbright
        {
            get {
                switch (GroupTreeType)
                {
                    case GroupTreeType.PbRight:
                        if (ViewState["GroupTree_pbright_j23oisdu9i"] == null)
                        {
                            if (string.IsNullOrWhiteSpace(Request["phonebookid"]))
                                return null;
                            DataSet ds  = PhoneBook.Group.PbRight.list(Request["phonebookid"]);
                            ViewState["GroupTree_pbright_j23oisdu9i"] = ds;
                        }
                        return ViewState["GroupTree_pbright_j23oisdu9i"] as DataSet;
                    case GroupTreeType.PbMember:
                        if (ViewState["GroupTree_pbmember_j23oisdu9i"] == null)
                        {
                            if (string.IsNullOrWhiteSpace(Request["phonebookid"]))
                                return null;
                            DataSet ds = PhoneBook.Group.PbMember.list(Request["phonebookid"]);
                            ViewState["GroupTree_pbmember_j23oisdu9i"] = ds;
                        }
                        return ViewState["GroupTree_pbmember_j23oisdu9i"] as DataSet;
                    default:
                        return null;
                }
                
            }
        }

        public Hashtable user
        {
            get
            {
                if (ViewState["GroupTree_user_so32ipohu43"] == null)
                    ViewState["GroupTree_user_so32ipohu43"] = PhoneBook.Users.Users.get(Commons.StrUtil.FormatValue(Session["userid"]));
                return ViewState["GroupTree_user_so32ipohu43"] as Hashtable;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Hashtable group = PhoneBook.Group.Group.get(Commons.StrUtil.FormatValue(user["groupid"]));

                if (group == null) return;

                setroot(group);
            }
        }

        protected void setroot(Hashtable group)
        {
            TreeNode groupnode = new TreeNode();
            groupnode.Text = Commons.StrUtil.FormatValue(group["groupname"]);
            groupnode.Value = "0|" + Commons.StrUtil.FormatValue(group["groupid"]);
            groupnode.PopulateOnDemand = true;
            groupnode.SelectAction = TreeNodeSelectAction.Expand;

            GroupTreeCtl.Nodes.Add(groupnode);
        }

        protected void PopulateNode(object sender, TreeNodeEventArgs e)
        {
            string strNodeValue = e.Node.Value;
            string strDepth = "";

            if (strNodeValue.IndexOf("|") >= 0)
            {
                strDepth = strNodeValue.Split('|')[0];
            }

            switch (strDepth)
            {
                case "0":
                    if (this.user["IsBOOper"] != DBNull.Value && Convert.ToBoolean(this.user["IsBOOper"]))
                    {
                        PopulateDepartment(e.Node);
                    }
                    PopulateDepartment(e.Node);
                    PopulateBranchOffice(e.Node);
                    break;
                case "1":
                    //PopulateEmployee(e.Node);
                    PopulateDepartment(e.Node);
                    break;
                case "2":
                    PopulateEmployee(e.Node);
                    break;
                default:
                    // Do nothing.
                    break;
            }

        }

        protected void PopulateDepartment(TreeNode node)
        {
            DataSet ResultSet = new DataSet();

            string strGroupId = string.Empty;

            bool isBONode = false;

            if (node.ValuePath.IndexOf("/") >= 0)
            {
                strGroupId = node.ValuePath.Split('/')[0].Split('|')[1];
                isBONode = true;
            }
            else
            {
                strGroupId = node.Value.Split('|')[1];
            }
            
            if (this.user["IsBOOper"] != DBNull.Value && Convert.ToBoolean(this.user["IsBOOper"]))
            {
                ResultSet = PhoneBook.Group.Department.list(strGroupId, Commons.StrUtil.FormatValue(this.user["bo"]));
            }
            else
            {
                if (isBONode)
                {
                    ResultSet = PhoneBook.Group.Department.list(strGroupId, node.Value.Split('|')[1]);
                }
                else
                {
                    ResultSet = PhoneBook.Group.Department.listforunit(strGroupId);
                }
            }

            if (Commons.DataUtil.IsValidate(ResultSet))
            {
                foreach (DataRow row in ResultSet.Tables[0].Rows)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = row["departmentname"].ToString();
                    newNode.Value = "2|" + row["departmentid"].ToString();

                    newNode.PopulateOnDemand = true;

                    newNode.SelectAction = TreeNodeSelectAction.Expand;
                    newNode.ShowCheckBox = true;
                    newNode.Expanded = false;

                    if (!string.IsNullOrWhiteSpace(Request["phonebookid"]))
                    {
                        newNode.Checked = IsRight(newNode.Value, "0");
                    }

                    node.ChildNodes.Add(newNode);
                }
            }

        }

        protected bool IsRight(string memberid, string righttype)
        {
            if (!EnabledPhRight || !Commons.DataUtil.IsValidate(pbright)) return false;

            string filter = string.Format("righttype = {0} and memberid = {1}", righttype, memberid);

            DataTable dt = Commons.DataUtil.DataFilter(pbright.Tables[0], filter, "");

            return Commons.DataUtil.IsValidate(dt);

        }

        protected void PopulateBranchOffice(TreeNode node)
        {
            DataSet ResultSet = new DataSet();
            if (this.user["IsBOOper"] != DBNull.Value && Convert.ToBoolean(this.user["IsBOOper"]))
            {
                ResultSet = PhoneBook.Group.BranchOffice.list(node.Value.Split('|')[1], Commons.StrUtil.FormatValue(this.user["bo"]));
            }
            else
            {
                ResultSet = PhoneBook.Group.BranchOffice.list(node.Value.Split('|')[1]);
            }

            if (Commons.DataUtil.IsValidate(ResultSet))
            {
                foreach (DataRow row in ResultSet.Tables[0].Rows)
                {
                    TreeNode NewNode = new TreeNode();
                    NewNode.Text = row["boname"].ToString();
                    NewNode.Value = "1|" + row["id"].ToString();

                    NewNode.PopulateOnDemand = true;

                    NewNode.SelectAction = TreeNodeSelectAction.Expand;
                    NewNode.ShowCheckBox = true;
                    NewNode.Expanded = false;

                    NewNode.Checked = IsRight(NewNode.Value, "2");

                    node.ChildNodes.Add(NewNode);
                }
            }
        }

        protected void PopulateEmployee(TreeNode node)
        {
            //DataSet ResultSet = PhoneBook.Group.Employee.list(node.Value);

            DataSet ResultSet = new DataSet();
            if (this.user["IsBOOper"] != DBNull.Value && Convert.ToBoolean(this.user["IsBOOper"]))
            {
                ResultSet = PhoneBook.Group.Employee.list(node.Value.Split('|')[1], Commons.StrUtil.FormatValue(this.user["bo"]));
            }
            else
            {
                ResultSet = PhoneBook.Group.Employee.list(node.Value.Split('|')[1]);
            }

            if (Commons.DataUtil.IsValidate(ResultSet))
            {
                foreach (DataRow row in ResultSet.Tables[0].Rows)
                {
                    TreeNode NewNode = new TreeNode();
                    NewNode.Text = row["employeename"].ToString();
                    NewNode.Value = row["employeeid"].ToString();

                    NewNode.PopulateOnDemand = false;

                    NewNode.SelectAction = TreeNodeSelectAction.None;
                    NewNode.ShowCheckBox = true;

                    NewNode.Checked = IsRight(NewNode.Value, "1");

                    node.ChildNodes.Add(NewNode);
                }
            }
        }

        public IList<string> GetSelDepartment()
        {
            IList<string> list = new List<string>();

            foreach (TreeNode node in GroupTreeCtl.Nodes[0].ChildNodes)
            {
                foreach (TreeNode enode in node.ChildNodes)
                {
                    if (enode.Checked)
                        list.Add(enode.Value);
                }
            }

            return list;
        }

        public IList<string> GetSelEmployee()
        {
            IList<string> list = new List<string>();

            foreach (TreeNode node in GroupTreeCtl.Nodes[0].ChildNodes)
            {
                foreach (TreeNode enode in node.ChildNodes)
                {
                    foreach (TreeNode fnode in enode.ChildNodes)
                    {
                        if (fnode.Checked)
                            list.Add(fnode.Value);
                    }
                }
            }

            return list;
        }

        public IList<string> GetSelBranchOffice()
        {
            IList<string> list = new List<string>();

            foreach (TreeNode node in GroupTreeCtl.Nodes[0].ChildNodes)
            {
                if (node.Checked)
                    list.Add(node.Value);
            }

            return list;
        }

    }

    public enum GroupTreeType
    {
        PbRight,
        PbMember
    }
}